package com.smart.core.starter.validate;

import org.springframework.validation.BindingResult;
import org.springframework.validation.FieldError;

import javax.validation.ConstraintViolation;
import java.util.Set;

/**
 * 格式化校验信息
 *
 * @author guxiaobai
 * @date 2018/11/28 20:54
 */

public class ValidateUtil {

    public static String toString(BindingResult result) {

        StringBuilder stringBuilder = new StringBuilder();
        for (FieldError fieldError : result.getFieldErrors()) {
            stringBuilder.append(fieldError.getField()).append(":").append(fieldError.getDefaultMessage()).append("|");
        }
        return stringBuilder.toString();
    }

    public static String toString(Set<ConstraintViolation<?>> violations) {
        StringBuilder stringBuilder = new StringBuilder();
        for (ConstraintViolation<?> constraintViolation : violations) {
            String path = constraintViolation.getPropertyPath().toString();
            stringBuilder.append(path.substring(path.indexOf(".") + 1)).append(constraintViolation.getMessage()).append("|");
        }
        return stringBuilder.toString();
    }
}
